package com.example.demo.controller;

import com.example.demo.bean.User;
import com.example.demo.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

@Controller  //方便起见，这里就用themyleaf模板
@CrossOrigin
public class controller {
    //建立hash表存储sessionid，session,当收到有cookie的请求时，找到cookie里的sessionid,就能拿到session,其实不用hashmap也行，
    //这里只是为了遍历出所有的session采用的hashmap,方便更好的理解session存储的原理.
    //因为session存储在服务器上，服务器重启后，session就会消失，而cookie存储在浏览器，cookie还会在。
    //如果cookie被浏览器清除了，那么Cookie[]cookies=request.getCookies();也会报空值异常。
    //注销登录的时候，不单单要把数据从hashmap里移除，还要把session删掉!!!!
    private HashMap<String, HttpSession> hash = new HashMap<>();

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/tologin")
    public String tologin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        try {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("sessionid")) {       //首先判断有没有sessionid，没有就去登录
                    HttpSession session = hash.get(cookie.getValue());  //因为hash表存的是session,session存的user，session以用户名为标识，即cookie的value
                    User user = (User) session.getAttribute(cookie.getValue()); //通过标识拿出存的user
                    response.getWriter().write("你的账号密码是" + user.getUsername() + "  " + user.getPassword());//测试用!
                }
                //遍历所有人的信息
                System.out.println("开始遍历所有数据");
                Iterator<String> iterator = hash.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    System.out.print(key + " ");
                    HttpSession session2 = hash.get(key);
                    User user2 = (User) session2.getAttribute(key);
                    System.out.println("账号密码是" + user2.getUsername() + "  " + user2.getPassword());
                }
            }
        } catch (NullPointerException e) {
            response.getWriter().write("没有session/cookie信息,可能是服务器重启或者浏览器清除cookie导致");
        }
        return "login.html";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = new User(username, password);
        int i = userMapper.login(user);
        if (i > 0) {
            //设置session，存入用户信息，标识为用户名，内容为用户名。
            HttpSession session = request.getSession();
            session.setAttribute(user.getUsername(), user);
            //设置cookie存入sessionid,存入用户名
            Cookie cookie = new Cookie("sessionid", username);
            cookie.setMaxAge(600);
            response.addCookie(cookie);
            //将数据存入hash表，hash表的key为用户名，内容为以用户名为标识存储用户信息的session
            hash.put(user.getUsername(), session);
//            HttpSession session1=hash.get(user.getUsername());
//            User  user1= (User) session1.getAttribute("user");
//            System.out.println(user1.getUsername());
            return "main.html";
        } else {
            return "login.html";
        }
    }

}
